import 'dart:async';

import 'package:lib_core/lib_core.dart';

extension FutureRspExt<T> on Future<Rsp<T>> {
  Future<T>? tryAwait([void Function(String err)? handleError]) async {
    Completer<T>? completer = Completer();
    then((rsp) {
      if (rsp.apiSuccess) {
        completer.complete(rsp.data);
      } else {
        throw rsp;
      }
    }).onError((error, stackTrace) {
      error.printError();
      stackTrace.printError();
      completer.complete(null);
      if (error is Rsp) {
        handleError?.call(error.errorMsg ?? '未知错误');
      } else if (error is TypeError) {
        handleError?.call('数据解析错误');
      } else {
        handleError?.call('未知错误');
      }
    });
    return completer.future;
  }
}

extension FutureExt<T> on Future<T> {
  Future<T>? tryAwaitCommon([void Function(String err)? handleError]) async {
    Completer<T>? completer = Completer();
    then((rsp) {
      if (rsp != null) {
        completer.complete(rsp);
      } else {
        throw Exception('result is null');
      }
    }).onError((error, stackTrace) {
      error.printError();
      stackTrace.printError();
      completer.complete(null);
      if (error is TypeError) {
        handleError?.call('数据解析错误');
      } else {
        handleError?.call('未知错误');
      }
    });
    return completer.future;
  }
}
